package com.linewell.license.demo.advice;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.linewell.license.demo.interceptor.CustomHandlerInterceptor;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
* @author
* Company:
* Createtime : 2018年8月30日 下午6:34:44
* Description : 
*/
@Configuration
public class WebConfigurerAdvice implements WebMvcConfigurer {

	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	/**
	 ** 编码设置注解，该方法只对POST有效，GET要通过改Tomcat下的配置才可以即添加URIEncoding="UTF-8"
	 * @return
	 */
	@Bean
	public FilterRegistrationBean characterEncodingFilterRegistration() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		//注入过滤器
		registration.setFilter(characterEncodingFilter);
		//拦截规则
		registration.addUrlPatterns("/*");
		//过滤器名称
		registration.setName("CharacterEncodingFilter");
		//过滤器顺序
		registration.setOrder(0);
		return registration;
	}

	/**
	 * 添加管理拦截器
	 * @param registry 拦截器注册器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多个拦截器组成一个拦截器链
		// addPathPatterns 用于添加拦截规则，/**表示拦截所有请求
		// excludePathPatterns 排除拦截
		registry.addInterceptor(new CustomHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/account/register");
	}

	/**
	 * * 使用fastjson作为json的解析器
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters(){
		//1.定义一个消息转换对象convert
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
		//2.添加fastJson配置信息，是否需要格式化
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(
				//结果是否格式化,默认为false
				SerializerFeature.PrettyFormat,
				//消除对同一对象循环引用的问题，默认为false
				SerializerFeature.DisableCircularReferenceDetect
		);
		// 处理中文乱码问题
		List<MediaType> fastMediaTypes = new ArrayList<>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		converter.setSupportedMediaTypes(fastMediaTypes);
		converter.setFastJsonConfig(fastJsonConfig);
		//3.在convert添加配置信息
		converter.setFastJsonConfig(fastJsonConfig);
		return new HttpMessageConverters(converter);
	}
}